<?php
if($_SESSION['login'] != true) {
	die('Access danied');
}
//------------------------------
if(IsSet($_POST['statement'])) {
	$statement = mb_strtolower($_POST['statement'],'UTF-8');;
}
if(IsSet($_POST['searchType'])) {
	$searchType = $_POST['searchType'];
}
if(IsSet($_POST['searchWordType'])) {
	$searchWordType = $_POST['searchWordType'];
}

if(IsSet($_POST['step'])) {
	$step = $_POST['step'];
} else if(IsSet($_GET['step'])) {
	$step = $_GET['step'];
}

if(IsSet($_GET['statementId'])) {
	$statementId = $_GET['statementId'];
}
if(IsSet($_GET['searcherId'])) {
	$searcherId = $_GET['searcherId'];
}
if(IsSet($_GET['urlId'])) {
	$urlId = $_GET['urlId'];
}
//------------------------------

if(!$step && (!$statement || $statement == '')) {
	/* wyswietl formularz */
	?>
	<script>
		$(document).ready(function(){ 
			$("input[name=searchType]").change(function() {
				var test = $(this).val();
				$(".desc").hide();
				$("#id"+test).show();
			}); 
		});
	</script>
	<form action="<?php echo $PHP_SELF; ?>" method="POST">
		<h3>Szukane hasło:</h3>
		<div style="clear: both; overflow: hidden; width: 400px; vertical-align: bottom;">
			<div style="float: left; text-align: left;">
				<input type="radio" name="searchType" value="1" checked="checked">równa się</input><br />
				<input type="radio" name="searchType" value="2">zaczyna się od</input><br />
				<input type="radio" name="searchType" value="3">kończy się na</input><br />
				<input type="radio" name="searchType" value="4">zawiera w sobie</input><br />
			</div>
			<div class="desc" id="id4" style="display: none; float: right; text-align: left;">
				<input type="radio" name="searchWordType" value="1">podany fragment</input><br />
				<input type="radio" name="searchWordType" value="2">każde słowo w podanej kolejnośći</input><br />
				<input type="radio" name="searchWordType" value="3">każde słowo w dowolnej kolejności</input><br />
				<input type="radio" name="searchWordType" value="4" checked="checked">przynajmniej jedno podane słowo</input><br />
			</div>
		</div>
		<br />
		<input type="hidden" name="step" value="1" />
		<input type="text" name="statement" size="60" />&nbsp;<input type="submit" value="Szukaj" />
	</form>
	<?php
} else if($step == 1 /*&& $statement != ''*/ ) {
	/* szukaj pasujacych fraz w bazie */
	$sql = "SELECT statement_id, statement FROM \"" . $configDbPrefix . "statements\" WHERE ";
	if($searchType == 1) {
		/* równa się */
		$sql .= "statement='$statement'";
	} else if($searchType == 2) {
		/* zaczyna się od */
		$sql .= "statement LIKE '" . $statement . "%'";
	} else if($searchType == 3) {
		/* kończy się na */
		$sql .= "statement LIKE '%" . $statement . "'";
	} else if($searchType == 4) {
		if($searchWordType > 1) {
			/* przygotowanie słów z ich lematami i formami fleksyjnymi */
			$tokens = explode(" ", $statement);
			$tokensNum = count($tokens);
			$wordsSql = "";
			$wordsNum = 0;
			for($i = 0 ; $i < $tokensNum ; $i++) {
				$wordsSql .= "'" . $tokens[$i] . "'";
				$wordsNum++;
				$wordsMap[$tokens[$i]] = true;
				if($i < $tokensNum - 1) {
					$wordsSql .= ",";
				}
			}
			//------------
			/* ew. dociagniecie lamtow */
			if($searchWordType == 2 || $searchWordType == 4) {
				$db->query("SELECT lemat FROM \"OMNIBUS_lematyzator\" WHERE word IN($wordsSql)");
				$rows = $db->fetchArray();
				foreach($rows as $row) {
					$lemat = $row['lemat'];
					if(!$wordsMap[$lemat]) {
						$wordsSql .= ",'$lemat'";
						$wordsMap[$lemat] = true;
					}
				}
				if($searchWordType == 4) {
					$tokens = explode(",", $wordsSql);
				}
			}
		}
		/* zawiera w sobie */
		if($searchWordType == 1) {
			$sql .= "statement LIKE '%" . $statement . "%'";
		} else if($searchWordType == 2) {
			
		} else if($searchWordType == 3) {
			$sql = "SELECT s.statement_id, statement FROM \"" . $configDbPrefix . "statements\" s JOIN \"OMNIBUS_statements_tokens\" st ON (s.statement_id = st.statement_id) JOIN \"OMNIBUS_tokens\" t ON (st.token_id = t.token_id) JOIN \"OMNIBUS_tokens_lemats\" tl ON (t.token_id = tl.token_id) JOIN \"OMNIBUS_lematyzator\" l ON (l.word_id = tl.word_id) WHERE t.token IN ($wordsSql) OR l.lemat IN ($wordsSql) GROUP BY s.statement_id HAVING count(*) = $wordsNum";
		} else if($searchWordType == 4) {
			$sql = "SELECT s.statement_id, statement FROM \"" . $configDbPrefix . "statements\" s JOIN \"OMNIBUS_statements_tokens\" st ON (s.statement_id = st.statement_id) JOIN \"OMNIBUS_tokens\" t ON (st.token_id = t.token_id) JOIN \"OMNIBUS_tokens_lemats\" tl ON (t.token_id = tl.token_id) JOIN \"OMNIBUS_lematyzator\" l ON (l.word_id = tl.word_id) WHERE t.token IN ($wordsSql) OR l.lemat IN ($wordsSql)";
		}
	}
	$sql .= " ORDER BY statement;";
	statementChooser($statement, $sql, 0, 0);
} else if($step == 2) {
	/* szukaj wynikow do podanej frazy */
	showResults($statementId, $searcherId);
} else if($step == 3) {
	/* wyswietlenie pozycji danego adresu w roznych wyszukiwarkach */
	showUrlInSearchers($urlId);
} else if($step == 4) {
	/* inne frazy, ktore maja w wynikach ten sam link */
	showStatementsWithTheSameUrlInResults($urlId);
} else {
	echo 'Błędne parametry';
}

/*
*	FUNKCJE
*/

/* wyswietla liste pasujacych fraz */
function statementChooser($statement, $sql, $addrUrl, $addrTitle) {
	global $db;
	global $configDbPrefix;
	$db->query($sql);
	$rows = $db->fetchArray();
	$resultNum = count($rows);
	//----------------------
	//pobranie listy wyszukiwarek
	$db->query("SELECT searcher_id, name, icon FROM \"" . $configDbPrefix . "searchers\" ORDER BY name ASC;");
	$searchers = $db->fetchArray();
	//----------------------
	if($statement || (!$addrUrl && !$addrTitle)) {
		?>
		Dla szukanego ciągu "<b><?php echo $statement; ?></b>" znaleziono <b><?php echo $resultNum; ?></b> pasujących haseł:
		<br />
		<?php
	} else {
		?>
		<a href="http://<?php echo $addrUrl; ?>" target="_blank"><b><?php echo $addrTitle; ?></b><br /><i><?php echo substr($addrUrl, 0, 70); ?></i></a>
		<br />
		występuje jeszcze w wynikach dla <b><?php echo $resultNum; ?></b> haseł:
		<br />
		<?php
	}
	
	if($rows) {
		?>
		<br />
		<table>
			<tr class="bgWhite">
				<th></td>
				<th>Pełne hasło</td>
				<th width="35%">Opcje</th>
			</tr>
			<?php
			$link = $PHP_SELF . '?configType=showResults&action=' . ACTION_SEARCH_STATEMENT . '&step=2&statementId=';
			$i = 0;
			foreach($rows as $row) {
				$i++;
				if($i % 2 == 0) {
					?>
					<tr class="bgWhite">
					<?php
				} else {
					?>
					<tr class="bgGray">
					<?php
				}
				?>
					<!-- kolejny numer -->
					<td width="5%"><?php echo $i . '.' ?></td>
					<!-- fraza -->
					<td><?php echo $row['statement']; ?></td>
					<!-- odnośniki -->
					<td>
						<a href="<?php echo $link . $row['statement_id']; ?>" title="Wyniki przetworzone"><img src="./images/world.png"/></a>
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<?php
						$searcherLink = $link . $row['statement_id'] . '&searcherId=';
						foreach($searchers as $searcherRow) {
							?>
							<a href="<?php echo $searcherLink . $searcherRow['searcher_id']; ?>" title="Wyniki szczegółowe z <?php echo $searcherRow['name']; ?>"><img src="./images/searchers/<?php echo $searcherRow['icon']; ?>"/></a>
							&nbsp;
							<?php
						}
						?>
					</td>
				</tr>
				<?php
			}
			?>
		</table>
	<?php
	}
}

/* wyswietla liste wynikow */
function showResults($statementId, $searcherId) {
	global $db;
	global $configDbPrefix;
	$db->query("SELECT statement FROM \"" . $configDbPrefix . "statements\" WHERE statement_id=$statementId;");
	$rows = $db->fetchArray();
	$statement = $rows[0]['statement'];
	//------------------------
	if($searcherId) {
		$db->query("SELECT name, icon FROM \"" . $configDbPrefix . "searchers\" WHERE searcher_id=$searcherId");
		$rows = $db->fetchArray();
		$searcherName = $rows[0]['name'];
		$searcherIcon = $rows[0]['icon'];
	}
	//------------------------
	if(!$searcherId) {
		/* wynik globalny */
		$db->query("SELECT u.url_id, u.global_rank as rank, a.url, a.title FROM \"" . $configDbPrefix . "urls\" u JOIN \"" . $configDbPrefix . "url_addrs\" a ON (u.addr_id =a.addr_id) WHERE u.statement_id=$statementId ORDER BY u.global_rank, a.title;");
	} else {
		/* przypadek dla konkretnej wyszukiwarki */
		$db->query("SELECT u.url_id, r.position as rank, a.url, a.title FROM \"" . $configDbPrefix . "urls\" u JOIN \"" . $configDbPrefix . "url_addrs\" a ON (u.addr_id =a.addr_id) JOIN \"" . $configDbPrefix . "results\" r ON (r.url_id = u.url_id) WHERE u.statement_id=$statementId AND r.searcher_id=$searcherId AND r.the_newest=1 ORDER BY r.position;");
	}
	$rows = $db->fetchArray();
	$resultNum = count($rows);
	//fraza i liczba pasujacych wynikow
	?>
	Znaleziono <b><?php echo $resultNum; ?></b> wyników dla hasła "<b><?php echo $statement; ?></b>":<br />
	<?php
	//tabelka z wynikami posortowana wg global_rank
	if($rows) {
		?>
		<br />
		<table>
			<tr class="bgWhite">
				<th>
					<?php
						if(!$searcherId) {
							?>
							<img src="./images/world.png" alt="Wyniki przetworzone" title="Wyniki przetworzone" />
							<?php
						} else {
							?>
							<img src="./images/searchers/<?php echo $searcherIcon; ?>" alt="<?php echo $searcherName; ?>" title="<?php echo $searcherName; ?>" />
							<?php
						}
					?>		
					&nbsp;Tytuł i adres
				</th>
				<th>Pozycja</th>
				<th width="8%">Opcje</th>
			</tr>
			<?php
			$link3 = $PHP_SELF . '?configType=showResults&action=' . ACTION_SEARCH_STATEMENT . '&step=3&urlId=';
			$link4 = $PHP_SELF . '?configType=showResults&action=' . ACTION_SEARCH_STATEMENT . '&step=4&urlId=';
			$i = 0;
			foreach($rows as $row) {
				$i++;
				if($i % 2 == 0) {
					?>
					<tr class="bgWhite">
					<?php
				} else {
					?>
					<tr class="bgGray">
					<?php
				}
				?>
					<!-- tytuł i adres -->
					<td><a href="http://<?php echo $row['url']; ?>" target="_blank">
						<b><?php echo $row['title']; ?></b>
						<br />
						<i><?php if(strlen($row['url']) > 70 ) { echo substr($row['url'], 0, 70) . '...'; } else { echo $row['url']; } ?></i>
					</a></td>
					<!-- pozycja -->
					<td><?php echo round($row['rank'], 3); ?></td>
					<!-- opcje -->
					<td>
						<a href="<?php echo $link3 . $row['url_id']; ?>" title="Dane szczegółowe"><img src="./images/details.gif"/></a>
						&nbsp;
						<a href="<?php echo $link4 . $row['url_id']; ?>" title="Powiązane hasła"><img src="./images/connection.gif"/></a>
					</td>
				</tr>
				<?php
			}
			?>
		</table>
	<?php
	}
}

function showUrlInSearchers($urlId) {
	global $db;
	global $configDbPrefix;
	$db->query("SELECT a.title, a.url FROM \"" . $configDbPrefix . "url_addrs\" a JOIN \"" . $configDbPrefix . "urls\" u ON (a.addr_id = u.addr_id) WHERE u.url_id=$urlId;");
	$rows = $db->fetchArray();
	$title = $rows[0]['title'];
	$url = $rows[0]['url'];
	//---------------------
	$db->query("SELECT s.name, s.url, s.icon, r.position, r.timestamp, r.the_newest FROM \"" . $configDbPrefix . "results\" r JOIN \"" . $configDbPrefix . "searchers\" s ON (r.searcher_id = s.searcher_id) WHERE r.url_id=$urlId ORDER BY s.name ASC, r.timestamp DESC;");
	$rows = $db->fetchArray();
	//informacja
	?>
	Dane szczegółowe (sztuk <b><?php echo count($rows); ?></b>) dla wyniku<br />
	<a href="http://<?php echo $url; ?>" target="_blank"><b><?php echo $title; ?></b><br /><i><?php if(strlen($url) > 70 ) { echo substr($url, 0, 70) . '...'; } else { echo $url; } ?></i></a>
	<br /><br />
	<?php
	//prezentacja wynikow
	$currentSearcher = '';
	$i = 0;
	$aaa = 0;
	//foreach($rows as $row) {
	for($rowId = 0 ; $rowId < count($rows) ; $rowId++) {
		$i++;
		$row = $rows[$rowId];
		$currentSearcher = $row['name'];
		?>
		<table>
			<tr class="bgWhite">
				<th width="40%">Wyniki z wyszukiwarki&nbsp;&nbsp;&nbsp;<img src="./images/searchers/<?php echo $row['icon']; ?>"><?php echo $row['name']; ?></td>
				<th>Data pobrania</th>
				<th></th>
				<th>Pozycja</th>
			</tr>
		<?php
		$i = 0;
		while($row['name'] == $currentSearcher) {
			$i++;
			if($i % 2 == 0) {
				?>
				<tr class="bgWhite">
				<?php
			} else {
				?>
				<tr class="bgGray">
				<?php
			}
			?>
				<td></td>
				<td><?php echo $row['timestamp']; ?></td>
				<td>
					<?php
						if($row['the_newest']) {
							?>
							<img src="./images/star.png" alt="Najnowszy" title="Najnowszy"/>
							<?php
						}
					?>
				</td>
				<td><?php echo $row['position']; ?></td>
			</tr>
				
			<?php
			$currentSearcher = $row['name'];
			$row = $rows[++$rowId];
		}
		$rowId--;
		?>
		</table>
		<br />
		<?php
	}
}

function showStatementsWithTheSameUrlInResults($urlId) {
	global $db;
	global $configDbPrefix;
	//-----------------------------
	$db->query("SELECT a.addr_id, a.url, a.title FROM \"" . $configDbPrefix . "urls\" u JOIN \"" . $configDbPrefix . "url_addrs\" a ON(u.addr_id = a.addr_id) WHERE u.url_id=$urlId;");
	$rows = $db->fetchArray();
	$addrId = $rows[0]['addr_id'];
	$addrUrl = $rows[0]['url'];
	$addrTitle = $rows[0]['title'];
	//-----------------------------
	$sql = "SELECT s.statement_id, s.statement FROM \"" . $configDbPrefix . "statements\" s JOIN \"" . $configDbPrefix . "urls\" u ON(s.statement_id = u.statement_id) WHERE u.addr_id=$addrId AND u.url_id!=$urlId ORDER BY s.statement;";
	
	statementChooser(0, $sql, $addrUrl, $addrTitle); 
	?>
	
	<!--<br />
	<?php
	if($rowsNum) {
		?>
		<table>
			<tr class="bgWhite">
				<th>Fraza</td>
				<th></td>
			</tr>
			<?php
			$link2 = $PHP_SELF . '?configType=showResults&action=' . ACTION_SEARCH_STATEMENT . '&step=2&statementId=';
			$i = 0;
			foreach($rows as $row) {
				$i++;
				if($i % 2 == 0) {
					?>
					<tr class="bgWhite">
					<?php
				} else {
					?>
					<tr class="bgGray">
					<?php
				}
				?>
				<td><a href="<?php echo $link2 . $row['statement_id']; ?>"><?php echo $row['statement']; ?></td>
				<td></td>
				<?php
			}
			?>
			</tr>	
		</table>-->
		<?php
	}
}

?>
